import { useParams } from 'react-router-dom';
import { Skeleton, Toast } from 'react-vant';
import { useEffect, useState } from 'react';
import useDetailStore from '@/store/useDetailStore';
import useCartStore from '@/store/useCartStore';
import useTitle from '@/hooks/useTitle';
import styles from './detail.module.css';
import { ArrowLeft, Cart, Minus, Plus, Star } from '@react-vant/icons';
import { Swiper, Image } from 'react-vant';

const ProductDetail = () => {
  const { id } = useParams();
  const { loading, detail, fetchDetail, selectedSku, setSelectedSku, quantity, setQuantity } = useDetailStore();
  const { addToCart } = useCartStore();
  const [activeTab, setActiveTab] = useState('details'); // details, specs, comments

  // 获取商品详情数据
  useEffect(() => {
    fetchDetail(id);
  }, [id]);

  // 设置页面标题
  useEffect(() => {
    useTitle(detail.title || '商品详情');
  }, [detail]);

  // 选择SKU
  const handleSkuSelect = (sku) => {
    setSelectedSku(sku);
  };

  // 减少数量
  const handleMinus = () => {
    if (quantity > 1) {
      setQuantity(quantity - 1);
    }
  };

  // 增加数量
  const handlePlus = () => {
    setQuantity(quantity + 1);
  };

  // 加入购物车
  const handleAddToCart = () => {
    if (!selectedSku) {
      Toast('请选择商品规格');
      return;
    }

    const cartItem = {
      id: detail.id,
      title: detail.title,
      price: selectedSku.price,
      image: detail.images[0]?.url,
      quantity: quantity,
      selectedSku: selectedSku
    };

    addToCart(cartItem);
    Toast('加入购物车成功');
  };

  // 渲染评分星星
  const renderRatingStars = (rating) => {
    return Array(5).fill(0).map((_, i) => (
      <Star
        key={i}
        size={16}
        color={i < rating ? '#ffb400' : '#ddd'}
        fill={i < rating ? '#ffb400' : 'transparent'}
      />
    ));
  };

  if (loading) return <Skeleton />;

  return (
    <div className={styles['detail-page']}>
      {/* 导航栏 */}
      <nav className={styles.nav}>
        <ArrowLeft fontSize={24} onClick={() => window.history.back()} />
        <Cart fontSize={24} />
      </nav>

      {/* 轮播图 */}
      <div className={styles['carousel-container']}>
        <Swiper>
          {detail.images?.map((item, index) => (
            <Swiper.Item key={index}>
              <Image lazyload src={item.url} style={{ width: '100%', height: '300px', objectFit: 'contain' }} />
            </Swiper.Item>
          ))}
        </Swiper>
      </div>

      {/* 商品信息 */}
      <div className={styles['info-container']}>
        <div className={styles.title}>{detail.title}</div>

        <div className={styles['price-container']}>
          <span className={styles['current-price']}>¥{selectedSku?.price || detail.price}</span>
          {detail.originalPrice && (
            <span className={styles['original-price']}>¥{detail.originalPrice}</span>
          )}
          {detail.discount && (
            <span className={styles.discount}>{detail.discount}</span>
          )}
        </div>

        <div className={styles['tags-container']}>
          {detail.tags?.map((tag, index) => (
            <span key={index} className={styles.tag}>{tag}</span>
          ))}
        </div>

        <div className={styles['delivery-info']}>
          <span>{detail.delivery || '普通快递'}</span>
          {detail.sales && <span style={{ marginLeft: '10px' }}>{detail.sales}</span>}
        </div>

        {/* SKU选择 */}
        {detail.skus && detail.skus.length > 0 && (
          <div className={styles['sku-section']}>
            <div className={styles['sku-title']}>选择规格</div>
            <div className={styles['sku-options']}>
              {detail.skus.map((sku) => (
                <div
                  key={sku.id}
                  className={`${styles['sku-option']} ${selectedSku?.id === sku.id ? styles.selected : ''}`}
                  onClick={() => handleSkuSelect(sku)}
                >
                  {sku.color} {sku.capacity}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 数量选择 */}
        <div className={styles['quantity-section']}>
          <div className={styles['quantity-title']}>数量</div>
          <div className={styles['quantity-control']}>
            <div className={styles['quantity-btn']} onClick={handleMinus}>
              <Minus size={18} />
            </div>
            <input
              type="number"
              className={styles['quantity-input']}
              value={quantity}
              min="1"
              onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value) || 1))}
            />
            <div className={styles['quantity-btn']} onClick={handlePlus}>
              <Plus size={18} />
            </div>
          </div>
        </div>

        {/* 加入购物车按钮 */}
        <button className={styles['add-to-cart-btn']} onClick={handleAddToCart}>
          加入购物车
        </button>
      </div>

      {/* 标签页 */}
      <div className={styles.tabs}>
        <div
          className={`${styles.tab} ${activeTab === 'details' ? styles.active : ''}`}
          onClick={() => setActiveTab('details')}
        >
          商品详情
        </div>
        <div
          className={`${styles.tab} ${activeTab === 'specs' ? styles.active : ''}`}
          onClick={() => setActiveTab('specs')}
        >
          规格参数
        </div>
        <div
          className={`${styles.tab} ${activeTab === 'comments' ? styles.active : ''}`}
          onClick={() => setActiveTab('comments')}
        >
          用户评价
        </div>
      </div>

      {/* 标签页内容 */}
      {activeTab === 'details' && (
        <div className={styles['details-content']}>
          <p>{detail.details || '暂无商品详情'}</p>
        </div>
      )}

      {activeTab === 'specs' && (
        <div className={styles['specs-container']}>
          {detail.specs?.map((spec, index) => (
            <div key={index} className={styles['spec-item']}>
              <div className={styles['spec-name']}>{spec.name}</div>
              <div className={styles['spec-value']}>{spec.value}</div>
            </div>
          )) || <p>暂无规格参数</p>}
        </div>
      )}

      {activeTab === 'comments' && (
        <div className={styles['comments-container']}>
          {detail.comments?.map((comment) => (
            <div key={comment.id} className={styles['comment-item']}>
              <div className={styles['comment-user']}>{comment.user}</div>
              <div className={styles['comment-rating']}>{renderRatingStars(comment.rating)}</div>
              <div className={styles['comment-content']}>{comment.content}</div>
              <div className={styles['comment-time']}>{comment.time}</div>
            </div>
          )) || <p>暂无用户评价</p>}
        </div>
      )}
    </div>
  );
};

export default ProductDetail;
